package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("dish")
public class DishController {

    @Autowired
    private DishService dishService;

    /**
     * 修改菜品
     */
    @PutMapping
    @CacheEvict(cacheNames = "dish",allEntries = true)//删除以dish开头的所有缓存
    public R<String> update(@RequestBody DishDto dto) {
        dishService.updateDishDto(dto);
        return R.success("修改成功");
    }

    /**
     * 分页查询
     */
    @GetMapping("/page")
    public R<Page<DishDto>> selectPage(Integer page, Integer pageSize, String name) {
        //调用service层自定义分页查询方法
        Page<DishDto> pageInfo = dishService.selectPage(page, pageSize, name);
        //返回page对象
        return R.success(pageInfo);
    }

    /**
     * 添加菜品
     */
    @PostMapping
    @CacheEvict(cacheNames = "dish",allEntries = true)//删除以dish开头的所有缓存
    public R<String> add(@RequestBody DishDto dishDto) {
        //调用自定义方法
        dishService.add(dishDto);
        //响应添加成功标识
        return R.success("添加成功");
    }

    /**
     * 根据id查询DishDto表
     */
    @GetMapping("/{id}")
    public R<DishDto> selectById(@PathVariable Long id) {
        DishDto dto = dishService.selectDishDtoById(id);
        return R.success(dto);
    }

    /**
     * 批量删除
     */
    @DeleteMapping
    @CacheEvict(cacheNames = "dish",allEntries = true)//删除以dish开头的所有缓存
    public R<String> deleteIds(Long[] ids) {

        dishService.deleteByIds(ids);

        return R.success("删除成功");
    }

    /**
     * 批量修改状态
     */
    @PostMapping("/status/{status}")
    public R<String> updateByStatus(@PathVariable Integer status, Long[] ids) {

        dishService.updateByStatus(status, ids);

        return R.success("修改状态成功");
    }

    @Autowired
    private CacheManager cacheManager;

    /**
     * 根据分类查询菜品列表
     */
    @GetMapping("/list")
    @Cacheable(cacheNames = "dish", key = "#categoryId+'_'+#name",unless = "#result.data.size()<=0")
    public R<List<DishDto>> selectList(Long categoryId, String name) {

        List<DishDto> dishDtos = dishService.selectList(categoryId, name);

        return R.success(dishDtos);

    }
}
